package service

import (
	"context"
	"inventory/api/inventory"
	"inventory/internal/model"
	"inventory/pkg/util"
)

// PreDeleteCheck 商品删除可行性咨询
func (s *Service) PreDeleteCheck(ctx context.Context, req *inventory.CheckProdDeleteRequest) (reply *inventory.CheckProdDeleteReply, err error) {
	var storages []*model.Storage
	if storages, err = s.dao.FindCanNotDeleteProducts(ctx, req.Ids); err != nil {
		return
	}
	views := make([]*inventory.CheckProdDeleteReply_Prod, len(storages))
	if len(storages) > 0 {
		warehouseIDMap := make(util.UInt32BoolMap)
		for _, storage := range storages {
			warehouseIDMap[storage.WarehouseID] = true
		}
		var warehouses []*model.Warehouse
		if warehouses, err = s.dao.FindWarehousesByIDs(ctx, warehouseIDMap.GetKeys(), req.SgId); err != nil {
			return
		}
		wm := make(map[uint32]string, len(warehouses))
		for _, w := range warehouses {
			wm[w.ID] = w.Name
		}
		for i, s := range storages {
			views[i] = &inventory.CheckProdDeleteReply_Prod{Id: *s.ProdID, WarehouseName: wm[s.WarehouseID]}
		}
	}
	reply = &inventory.CheckProdDeleteReply{Prods: views}
	return
}
